<?php

declare(strict_types=1);

namespace app\shop\controller;

use app\shop\controller\Base;
use app\model\Column;
use think\facade\Request;
use app\model\Users;
use app\validate\UsersVal;
use think\exception\ValidateException;

/**
 * @name 登录类
 */
class Login extends Base
{
    /**
     * @name 登录/注册
     */
    public function logorreg()
    {
        if (request()->isPost()) {
            $param = Request::param();
            try { //进入验证
                validate(UsersVal::class)->scene('login')->check($param);
            } catch (ValidateException $e) {
                return json(['code' => 1, 'val' => $e->getError()]);
            }
            $mob = Users::where([['mobile', '=', $param['mobile']]]);
            if ($mob) {
                if ($mob['is_black'] == "1") {
                    return json(['code' => 2, 'msg' => '该账号已被拉黑，请联系客服!']);
                }
                $find = Users::where([['mobile', '=', $param['mobile']], ['password', '=', $this->md5_salt($param['password'])]]);
                if ($find) {
                    $find['last_login'] = time();
                    $find['last_ip'] = request()->ip();
                    Users::edit($find);
                    return json(['code' => 0, 'token' => $this->signToken($find['id'], $find['mobile'])]);
                } else {
                    return json(['code' => 2, 'msg' => '账号或密码错误']);
                }
            } else {
                $param['password'] = $this->md5_salt($param['password']);
                $param['last_login'] = time();
                $param['last_ip'] = request()->ip();
                $resid = Users::addid($param);
                if ($resid > 0) {
                    return json(['code' => 0, 'token' => $this->signToken($resid, $param['mobile'])]);
                } else {
                    return json(['code' => 2, 'msg' => '操作失败']);
                }
            }
        }
    }
}
